
package com.kugou.game.sdk.ui.fragment;

import com.kugou.framework.base.BaseWorkerFragment;
import com.kugou.game.sdk.api.common.User;
import com.kugou.game.sdk.core.SDKActions;
import com.kugou.game.sdk.core.UserManager;
import com.kugou.game.sdk.interfaces.OnRequestListener;
import com.kugou.game.sdk.ui.widget.LoadingView;
import com.kugou.game.sdk.utils.AppUtil;
import com.kugou.game.sdk.utils.NetWorkUtil;
import com.kugou.game.sdk.utils.Rx;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Message;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnFocusChangeListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

/**
 * 描述:第三方账号登录补填密码
 *
 * @author jamywang
 * @since 2015年12月9日 下午2:30:43
 */
public class SetLoginPsdFragment extends BaseWorkerFragment {

    private static final int MSG_ADD_PASSWORD = 0;

    private static final int MSG_ADD_PASSWORD_SUCCESS = 1;

    private static final int MSG_ADD_PASSWORD_FAILE = 2;

    public static final String USER_PASSWORD_KEY = "user_password_key";

    private Activity context;

    private User user;

    private View layoutFormalView;

    private LinearLayout layoutResult;

    private LoadingView mLoadingView;

    private EditText etNewPassWord, etPassWordAgain;

    private TextView tvPswTop, tvPswTips, tvPswTipsAgain;

    private Button btnSubmit, btnBackToGame;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        context = getActivity();
        user = UserManager.getInstance().getCurrentUserInternal();
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(Rx.layout.kg_fragment_add_password, null);
        initView(view);
        return view;
    }

    private void initView(View view) {
        mLoadingView = (LoadingView) view.findViewById(Rx.id.kg_loading);
        layoutFormalView = view.findViewById(Rx.id.kg_layout_add_user_password);
        layoutResult = (LinearLayout) view.findViewById(Rx.id.kg_layout_summit_successed);
        tvPswTop = (TextView) view.findViewById(Rx.id.kg_tv_add_psw_top);
        tvPswTop.setText("亲爱的" + user.getAccountName()
                + "，由于您的账户是第三方账户授权登录账号，请务必完成补填登录密码事项，从而更全面的享受我们给您提供的功能与服务。");
        tvPswTips = (TextView) view.findViewById(Rx.id.kg_tv_add_password_tips);
        tvPswTips.setVisibility(View.INVISIBLE);
        tvPswTipsAgain = (TextView) view.findViewById(Rx.id.kg_tv_add_password_again_tips);
        tvPswTipsAgain.setVisibility(View.INVISIBLE);
        etNewPassWord = (EditText) view.findViewById(Rx.id.kg_et_add_password);
        etNewPassWord.setOnFocusChangeListener(new OnFocusChangeListener() {

            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                String str = etNewPassWord.getText().toString();
                if (!TextUtils.isEmpty(str)) {
                    checkNewPassword();
                }
            }
        });
        etPassWordAgain = (EditText) view.findViewById(Rx.id.kg_et_add_password_again);
        etPassWordAgain.setOnFocusChangeListener(new OnFocusChangeListener() {

            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if (hasFocus) {
                    tvPswTipsAgain.setVisibility(View.INVISIBLE);
                } else {
                    isPasswordSame();
                }
            }
        });

        // 提交按钮
        btnSubmit = (Button) view.findViewById(Rx.id.kg_btn_summit);
        btnSubmit.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                submit();
            }
        });

        // 修改成功后 返回游戏按钮
        btnBackToGame = (Button) view.findViewById(Rx.id.kg_btn_back_to_the_game);
        btnBackToGame.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                context.sendBroadcast(new Intent(SDKActions.ACTION_BACK_TO_GAME));
                context.finish();
            }
        });

    }

    /**
     * 点击提交
     */
    private void submit() {
        if (!NetWorkUtil.isNetworkAvailable(context)) {
            showToast("请检查您的网络连接");
            return;
        }

        hideSoftInput(context);
        etNewPassWord.clearFocus();
        etPassWordAgain.clearFocus();
        if (checkNewPassword() && isPasswordSame()) {
            showLoadingView();
            sendEmptyBackgroundMessage(MSG_ADD_PASSWORD);
        }
    }

    /**
     * 检查新密码输入是否正确
     * 
     * @return
     */
    private boolean checkNewPassword() {
        String text = etNewPassWord.getText().toString();
        if (isPasswordCorrect(text)) {
            tvPswTips.setVisibility(View.INVISIBLE);
            return true;
        } else {
            tvPswTips.setVisibility(View.VISIBLE);
            return false;
        }
    }

    /**
     * 验证密码格式
     * 
     * @param password
     * @return
     */
    private boolean isPasswordCorrect(String password) {
        if (!TextUtils.isEmpty(password)) {
            // 使用手机酷狗的密码判断规则
            if (password.length() > 16 || password.length() < 6) {
                showToast("请设置6-16位字母/数字的密码");
                return false;
            } else if (AppUtil.isSpatialChart(password) || AppUtil.isHaveChinese(password)) {
                showToast("密码不能包含：空格、符号等特殊字符");
                return false;
            } else {
                return true;
            }
        }
        return false;
    }

    /**
     * 检查两次输入密码是否一致
     */
    private boolean isPasswordSame() {
        String psw1 = etNewPassWord.getText().toString();
        String psw2 = etPassWordAgain.getText().toString();
        if (!psw1.equals(psw2)) {
            tvPswTipsAgain.setVisibility(View.VISIBLE);
            return false;
        } else {
            tvPswTipsAgain.setVisibility(View.INVISIBLE);
            return true;
        }
    }

    /**
     * 正在加载时的页面显示
     */
    private void showLoadingView() {
        layoutFormalView.setVisibility(View.GONE);
        layoutResult.setVisibility(View.GONE);
        mLoadingView.setVisibility(View.VISIBLE);
    }

    /**
     * 正常情况的页面显示
     */
    private void showFormalView() {
        layoutFormalView.setVisibility(View.VISIBLE);
        layoutResult.setVisibility(View.GONE);
        mLoadingView.setVisibility(View.GONE);
    }

    /**
     * 修改成功后的页面显示
     */
    private void showResultView() {
        layoutFormalView.setVisibility(View.GONE);
        layoutResult.setVisibility(View.VISIBLE);
        mLoadingView.setVisibility(View.GONE);
    }

    @Override
    public void handleBackgroundMessage(Message msg) {
        switch (msg.what) {
            case MSG_ADD_PASSWORD:
                // 请求相关参数
                String userName = user.getAccountName();
                String newPassword = etNewPassWord.getText().toString();
                // 发送请求
                final Message message = new Message();
                UserManager.getInstance().setLoginPsd(userName, newPassword,
                        new OnRequestListener() {

                            @Override
                            public void onSuccess() {
                                message.what = MSG_ADD_PASSWORD_SUCCESS;
                            }

                            @Override
                            public void onFailed(String errorMsg) {
                                message.what = MSG_ADD_PASSWORD_FAILE;
                                message.obj = errorMsg;
                            }
                        });
                sendUiMessage(message);
                break;
        }
    }

    @Override
    public void handleUiMessage(Message msg) {
        switch (msg.what) {
            case MSG_ADD_PASSWORD_SUCCESS:
                showResultView();
                Intent intent = new Intent(SDKActions.ACTION_SET_LOGIN_PSD_SUCCESS);
                context.sendBroadcast(intent);
                break;
            case MSG_ADD_PASSWORD_FAILE:
                String errorMsg = (String) msg.obj;
                showFormalView();

                if (!TextUtils.isEmpty(errorMsg)) {
                    showToast(errorMsg);
                }
                break;
            default:
                break;
        }
    }

}
